<template>
  <div class="table-wrap">
    <div class="table-search flex flex-row">
      <div class="search-wrap">
        <div class="item-wrap">
          <div class="search-item">
            <span class="search-item-prefix">用户查询</span>
            <Input placeholder="输入关键字查询" style="width: 215px" allowClear
              v-model:value="pageRequest.search!.name"></Input>
          </div>
          <div class="search-item">
            <span class="search-item-prefix">所属企业</span>
            <Input placeholder="输入关键字查询" style="width: 215px" allowClear
              v-model:value="pageRequest.search!.companyName"></Input>
          </div>

          <div class="search-item">
            <span class="search-item-prefix">创建时间</span>
            <RangePicker :placeholder="['请选择日期', '请选择日期']" style="width: 215px" v-model:value="createDateRangeValue"
              @change="handleCreateRang" allowClear format="YYYY-MM-DD" />
          </div>
          <div class="search-item">
            <span class="search-item-prefix">最近登录</span>
            <RangePicker :placeholder="['请选择日期', '请选择日期']" style="width: 215px" v-model:value="loginDateRangeValue"
              @change="handleLoginRang" allowClear format="YYYY-MM-DD" />
          </div>
        </div>
        <div class="search-btn">
          <Button type="primary" class="!flex flex-row items-center" @click="getUserList">
            <template #icon>
              <SearchOutlined class="!flex" />
            </template>查询
          </Button>
          <Button type="default" @click="handleReset">重置</Button>
        </div>
      </div>

      <div class="select-wrap">
        <div class="select-item" v-if="createTimeType">
          <span class="search-item-prefix">注册时间</span>
          <div class="tags-item">
            <CheckableTag v-for="(item, index) in createTimeType" :key="index" :checked="item.checked"
              @click="() => handlerCreateState(item.value)">
              {{ item.label }} {{ item.count ? `(${item.count})`  :'' }} </CheckableTag>
          </div>
        </div>
        <div class="select-item" v-if="loginTimeType">
          <span class="search-item-prefix">登录时间</span>
          <div class="tags-item">
            <CheckableTag v-for="(item, index) in loginTimeType" :key="index" :checked="item.checked"
              @click="() => handlerLoginState(item.value)">
              {{ item.label }} {{ item.count ? `(${item.count})`  :'' }} </CheckableTag>
          </div>
        </div>
      </div>
    </div>
    <div class="table-content">
      <div class="table-add-btn">
        <span>共{{ accountDatasource && accountDatasource.count }}个企业用户</span>
      </div>
      <Table :columns="userColumns" :data-source="accountDatasource && accountDatasource.items" row-key="id"
        :pagination="{
          pageSize: pageRequest.page!.pageSize,
          total: accountDatasource?.count,
          pageSizeOptions: pageSizeOptions,
          showSizeChanger: true,
        }" :loading="loading" @change="onChange">
        <template #bodyCell="{ column, record }">

          <template v-if="column.key === 'name'">
            <div @click="handleDrawerOpen(record)" class="cursor-pointer text-[#0960bd]">{{ record.name || '--' }}
            </div>
          </template>

          <template v-if="column.key === 'loginCompanyName'">
            <div>{{ record.loginCompanyName || '--' }}</div>
          </template>


          <template v-if="column.key === 'mobile'">
            <div> {{ formatPhoneNumberStrict(record.mobile) }} </div>
          </template>

          <template v-if="column.key === 'createTime'">
            <span>{{ convertTime(record.createTime, 'YYYY-MM-DD HH:mm') }}</span>
          </template>
          <template v-if="column.key === 'loginTime'">
            <span>{{ convertTime(record.loginTime, 'YYYY-MM-DD HH:mm') }}</span>
          </template>

          <template v-if="column.key === 'state'">
            <span>{{ record.state === EnumCompanyState.冻结 ? '冻结' : '正常' }}</span>
          </template>
        </template>
      </Table>
    </div>
    <DrawerModal ref="detailRef" @ok="handleDrawOk" @cancel="handleCloseDrawer" :userData="userData" />
  </div>
</template>

<script lang="ts" setup name="UserManagement">
import { ref } from 'vue'
import { SearchOutlined } from '@ant-design/icons-vue'
import { userColumns } from './index'
import { Input, Button, Table, Tag, RangePicker } from 'ant-design-vue'
import {
  CompanyQueryUserRequestPageSearchRequest,
  CompanyQueryUserResult,
  CompanyQueryUserResultCompanyQueryUserStatResultPageListModel,
  CompanyUserApi,
  Int32SelectCheckableTag,
  EnumCompanyState
} from '@/api'
import { Dayjs } from 'dayjs';
import { convertTimeChange, convertTime, formatPhoneNumberStrict } from '@/utils/queryConversion'
import DrawerModal from "./DrawerModal.vue"

const { CheckableTag } = Tag;

type RangeValue = [Dayjs, Dayjs] | [string, string] | undefined;

const loading = ref(false)
const pageRequest = reactive<CompanyQueryUserRequestPageSearchRequest>({
  page: {
    pageIndex: 1,
    pageSize: 20,
  },
  search: {},
  sort: {
    field: '',
    reverse: true,
  },
});
const pageSizeOptions = ref<string[]>(['5', '10', '20', '50', '100']);
// 状态
const isLock = ref()
// 列表数据
const accountDatasource = ref<CompanyQueryUserResultCompanyQueryUserStatResultPageListModel>()
// 日期范围选择
const createDateRangeValue = ref<RangeValue>();
// 日期范围选择
const loginDateRangeValue = ref<RangeValue>();
// 注册时间
const createTimeType = ref<Int32SelectCheckableTag[] | undefined>();
// 登录时间
const loginTimeType = ref<Int32SelectCheckableTag[] | undefined>();
// 详情
const detailRef = ref();

// 重置
function handleReset() {
  pageRequest.search = {}
  isLock.value = undefined;

  createDateRangeValue.value = undefined;
  loginDateRangeValue.value = undefined;
  createTimeType.value!.forEach((v, i) => {
    if (i === 0) {
      v.checked = true;
    } else {
      v.checked = false;

    }
  });
  loginTimeType.value!.forEach((v, i) => {
    if (i === 0) {
      v.checked = true;
    } else {
      v.checked = false;
    }
  });

  getUserList();
}

// 获取列表
const getUserList = async () => {
  loading.value = true;
  try {
    let res = await CompanyUserApi.companyuserUserlist(pageRequest);
    accountDatasource.value = res;
    createTimeType.value = res.extend?.createTimes;
    loginTimeType.value = res.extend?.loginTimes;

    if (editId.value) {
      let userItem = res.items?.filter(v => v.id === editId.value);
      userData.value = userItem ? userItem[0] : undefined;
    }
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
}

// 时间搜索
function handleCreateRang() {
  let time = convertTimeChange(createDateRangeValue.value, 'YYYY-MM-DD');
  pageRequest.search!.createTimeStart = time.startTime;
  pageRequest.search!.createTimeEnd = time.endTime;
}
function handleLoginRang() {
  let time = convertTimeChange(loginDateRangeValue.value, 'YYYY-MM-DD');
  pageRequest.search!.loginTimeStart = time.startTime;
  pageRequest.search!.loginTimeEnd = time.endTime;
}

// 注册时间
function handlerCreateState(id?: number) {
  createTimeType.value!.forEach(v => {
    if (v.value === id) {
      v.checked = true;
    } else {
      v.checked = false;
    }
  })
  pageRequest.search!.createTimeType = id ? id : undefined;
  getUserList();
}
function handlerLoginState(id?: number) {
  loginTimeType.value!.forEach(v => {
    if (v.value === id) {
      v.checked = true;
    } else {
      v.checked = false;
    }
  })
  pageRequest.search!.loginTimeType = id ? id : undefined;
  getUserList();
}

onMounted(() => {
  getUserList();
})


const userData = ref();
const editId = ref();
// 详情
const handleDrawerOpen = (data: CompanyQueryUserResult) => {
  userData.value = data;
  editId.value = data.id;
  detailRef.value.handleOpen(data);
}

function handleDrawOk() {
  getUserList();
}

function handleCloseDrawer() {
  userData.value = undefined;
  editId.value = undefined;
}

function onChange(pagination: any, filters: any, sorter: any,) {
  pageRequest.page!.pageIndex = pagination.current;
  pageRequest.page!.pageSize = pagination.pageSize;

  pageRequest.sort!.field = sorter.order ? sorter.field : '';
  pageRequest.sort!.reverse = sorter.order == 'descend';
  getUserList();
}

</script>

<style lang="less" scoped></style>